package Lee_code;

import static jdk.nashorn.internal.objects.NativeArray.reduce;

/**
 * @author blh
 * @date 2024年07月01日 13:46
 */
public class Lee_221_71 {
    public int maximalSquare(char[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int max = 0;
        int[][] dp = new int[m][n];

        // 初始化
        for (int i = 0; i < n; i++) {
            if (matrix[0][i] == '1') {
                dp[0][i] = 1;
            }
        }
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == '1') {
                dp[i][0] = 1;
            }
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == '1') {
                    // 以matrix[i][j]为结尾
                    int bian = 1;
                    int tempMax = Math.min(i, j) + 1;
                    for (int k = 2; k <= tempMax; k++) {
                        if (judgeSquare(i, j, k, matrix)) {
                            bian++;
                        } else {
                            break;
                        }
                    }
                    dp[i][j] = Math.max(dp[i][j - 1], bian);
                    max = Math.max(max, dp[i][j]);
                } else {
                    dp[i][j] = dp[i][j - 1];
                }
            }
        }
        return max * max;
    }

    private boolean judgeSquare(int row, int column, int k, char[][] matrix) {

        for (int i = row; i >= row - k + 1; i--) {
            for (int j = column; j >= column - k + 1; j--) {
                if (matrix[i][j] == '0') {
                    return false;
                }
            }
        }
        return true;
    }
}
